package com.myway.core.jersey.exception;

import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import com.myway.utils.PropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;

import com.myway.dto.utils.MsgUtil;
import com.myway.utils.Message;
import com.google.gson.JsonSyntaxException;

/**
 * 类名称：ExceptionMapperSupport <br/>
 * 类描述：统一的异常处理 <br/>
 * 创建时间：2016年1月19日 上午11:29:12 <br/>
 * @author 张涛
 * @version V1.0
 */
@Provider
public class ExceptionMapperSupport implements ExceptionMapper<Exception> {

	private static final Logger log = Logger.getLogger(ExceptionMapperSupport.class);

	private static final String CONTEXT_ATTRIBUTE = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;

	Status statusCode = Status.INTERNAL_SERVER_ERROR;
	
	@Context
    private HttpServletRequest request;
	@Context  
    private ServletContext servletContext;
	 
	
	/**
	 * 名称：toResponse <br/>
	 * 描述： //全局异常统一处理,个别异常分别自行处理,但不要过于细节化,劲量定义自身异常结构,全局使用全局结构<br/>
	 * 		//如果可以使用mvc的读取pro机制自动进行文件读取转换当然是最好,记住为啥现在的代码结构无法进行相应的转换 
	 *  	//其他异常暂时全部为系统内部调用,抛出的异常<br/>
	 * @param exception
	 * @return
	 * @see ExceptionMapper#toResponse(Throwable)
	 */
	@Override
	@SuppressWarnings("unused")
	public Response toResponse(Exception exception) {
		log.error("----------------------------Error Info-------------------------------");
		WebApplicationContext context = (WebApplicationContext)servletContext.getAttribute(CONTEXT_ATTRIBUTE);
		String form = request.getHeader(SecurityContext.FORM_AUTH);
		String errorCode = exception.getMessage();
		if(!StringUtils.isNumeric(errorCode)){
			if(exception instanceof JsonSyntaxException){
				errorCode = Message.PARAM_INVALID.getAlias();
			}
			else{
				errorCode = Message.UNKNOWN.getAlias();
			}
		}
		Properties msgProperties = PropertiesUtil.msgProperties;
		String errorInfo = PropertiesUtil.getProStr(msgProperties, errorCode);
		String returnMsg = MsgUtil.returnError(errorCode,errorInfo);
		log.error("FORM:"+form);
		log.error("ERROR_CODE:"+errorCode+",errorInfo"+returnMsg);
		log.error("STACK_TRACE:",exception);
//		return Response.ok(returnMsg, MediaType.TEXT_PLAIN).status(statusCode).build();
		return Response.ok(returnMsg, MediaType.TEXT_PLAIN).build();
	}
	
}
